﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace Dexter.Services.Helpers
{
	/// <summary>
	/// COntains some helper classes that can be used by services implementaions and other classes
	/// </summary>
	public class PostHelpers
	{
		public static string[] RetrieveTagsFromBody(string html)
		{
			var relRegex = new Regex(@"\s+rel\s*=\s*(""[^""]*?\btag\b.*?""|'[^']*?\btag\b.*?')", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			var hrefRegex = new Regex(@"\s+href\s*=\s*(""(?<url>[^""]*?)""|'(?<url>[^']*?)')", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			var anchorRegex = new Regex(@"<a(\s+\w+\s*=\s*(?:""[^""]*?""|'[^']*?')(?!\w))+\s*>.*?</a>", RegexOptions.IgnoreCase | RegexOptions.Singleline);

			var tags = new Collection<string>();
			var loweredTags = new Collection<string>();

			foreach (Match m in anchorRegex.Matches(html))
			{
				string anchorHtml = m.Value;
				if (!relRegex.IsMatch(anchorHtml))
				{
					continue;
				}

				Match urlMatch = hrefRegex.Match(anchorHtml);
				if (urlMatch.Success)
				{
					string urlStr = urlMatch.Groups["url"].Value;
					if (urlStr.EndsWith("/default.aspx", StringComparison.InvariantCultureIgnoreCase))
					{
						urlStr = urlStr.Substring(0, urlStr.Length - 13);
					}
					Uri url;
					if (Uri.TryCreate(urlStr, UriKind.RelativeOrAbsolute, out url))
					{
						string[] seg = url.Segments;
						string tag = HttpUtility.UrlDecode(seg[seg.Length - 1].Replace("/", ""));

						//Keep a list of lowered tags so we can prevent duplicates without modifying capitalization
						string loweredTag = tag.ToLower();
						if (!loweredTags.Contains(loweredTag))
						{
							loweredTags.Add(loweredTag);
							tags.Add(tag);
						}
					}
				}
			}
			return tags.ToArray();
		}

		/// <summary>
		/// 	tries to give a shape to unformatted messages, this is a very situational
		/// 	function to use
		/// </summary>
		/// <param name = "html"></param>
		/// <returns></returns>
		public static string PreProcessUnformattedMessages(string html)
		{
			return html.Replace(".\r\n\r\n", ".<br /><br />");
		}
	}
}
